//
//  ZDBBindingAlipayViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/17.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBBindingAlipayViewController.h"
#import "SC_ActionSheet.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "HUPhotoBrowser.h"
@interface ZDBBindingAlipayViewController ()<TZImagePickerControllerDelegate,UITextFieldDelegate>
@property(strong,nonatomic)NSString * kUploadIconImageToken;
@property(strong,nonatomic)UIImage * selectImage;
@property(strong,nonatomic)UIImageView * imageVIEW;
@property(assign,nonatomic)BOOL isEditicon;//是否编辑个二维码图片
@end
@implementation ZDBBindingAlipayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
     NSDictionary * userDic = [[DJLoginHelper sharedInstance] cj_UserDicc];
    _isBindAlipay = NO;
    _isEditicon = NO;
    [self getAvatarQiniuToken];
    [self.bindBtn add_BtnClickHandler:^(NSInteger tag) { //绑定支付包
           
           [self uploadBindAlipay];
       
    }];
    if (!kStringIsEmpty(userDic[@"zfbNumber"])) {
        _isBindAlipay = YES;
    }
    if (!_isBindAlipay) {
        [self.addBtn add_BtnClickHandler:^(NSInteger tag) {//添加支付宝照片
            [self uploadImage];
        }];
    }else
    {
        self.navigationItem.title = @"编辑支付宝";
        _nameTextField.text = userDic[@"zfbName"];
        _numberTextField.text = userDic[@"zfbNumber"];
        NSString * url = userDic[@"zfbImage"];
        [self.addBtn sd_setImageWithURL:[NSURL URLWithString:url] forState:0 placeholderImage:[UIImage imageNamed:@"add_alipay"]];
        [self.bindBtn setTitle:@"确认" forState:0];
        [self.addBtn add_BtnClickHandler:^(NSInteger tag) {//添加支付宝照片
           [self uploadImage];
            
        }];
    }
   
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    return NO;
}
- (void)uploadBindAlipay
{
    WeakSelf
    if (_isBindAlipay) {
        NSDictionary * userDic = [[DJLoginHelper sharedInstance] cj_UserDicc];
        if ([_numberTextField.text isEqualToString:userDic[@"zfbNumber"]] && !_isEditicon)//同一个并且没有修改二维码就rentrn回去
        {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            return;
        }
        
    }
    if (!_selectImage)
    {
        [JMNotifyView showNotify:@"请选择上传支付宝收款码" isSuccessful:NO];
        return;
    }
    if (kStringIsEmpty(_nameTextField.text))
    {
        [JMNotifyView showNotify:@"请输入微信昵称" isSuccessful:NO];
        return;
    }
    if (kStringIsEmpty(_numberTextField.text))
    {
        [JMNotifyView showNotify:@"请输入微信账号" isSuccessful:NO];
        return;
    }
    if ([ZBDUnit JudgeTheillegalCharacter:_nameTextField.text])
    {
        [JMNotifyView showNotify:@"昵称不能包含特殊字符" isSuccessful:NO];
        return;
    }
   
    if (self.kUploadIconImageToken)
    {
         self.bindBtn.userInteractionEnabled = NO;
         [self showLoadingAnimation];
       [self upLoadImageToQINiu:weakSelf.selectImage andBlock:^(NSString *imageKey) {
            NSLog(@"imageKey----%@",imageKey);
          
           NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
           [diccc setValue:imageKey forKey:@"zfbImage"];
           [diccc setValue:weakSelf.nameTextField.text forKey:@"zfbName"];
           [diccc setValue:weakSelf.numberTextField.text forKey:@"zfbNumber"];
           
           WeakSelf
           NSString  * bandZfbNumber = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"bandZfbNumber"];
           [[SmileHttpTool sharedInstance] POST:bandZfbNumber parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
               if (statusCode ==0) {
                   if (!weakSelf.isBindAlipay) {
                        [JMNotifyView showNotify:@"绑定成功" isSuccessful:NO];
                   }else
                   {
                        [JMNotifyView showNotify:@"编辑成功" isSuccessful:NO];
                   }
                   NSDictionary * userDic = [[DJLoginHelper sharedInstance] cj_UserDicc];
                   NSMutableDictionary * dataDicc = [NSMutableDictionary dictionaryWithDictionary:userDic];
                   [dataDicc setValue:weakSelf.nameTextField.text  forKey:@"zfbName"];
                   [dataDicc setValue:weakSelf.numberTextField.text  forKey:@"zfbNumber"];
                   [[DJLoginHelper sharedInstance] save_UserInfo:dataDicc];  
                   if (weakSelf.updetaInfoClickBlock) {
                       weakSelf.updetaInfoClickBlock(YES);
                   }
                   [weakSelf.navigationController popViewControllerAnimated:YES];
               }else
               {
                   [JMNotifyView showNotify:message isSuccessful:NO];;
               }
               [self stopLoadingAnimation];
                self.bindBtn.userInteractionEnabled = YES;
           } failure:^(id responseObject, NSError *error) {
               [self stopLoadingAnimation];
           }];
        }];
    }else
    {
        [self getAvatarQiniuToken];
    }
    
}
// 上传照片
- (void)uploadImage {
   
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingGif = NO;
    if (@available(iOS 13.0, *)) {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
        
    }
    imagePickerVc.alwaysEnableDoneBtn = YES;
    imagePickerVc.allowPickingVideo = NO; //不许选择视频
    imagePickerVc.allowPickingMultipleVideo = NO;//不允许选择视频gif
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#333333"];
    imagePickerVc.naviTitleColor = [UIColor colorWithHexString:@"#333333"];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    WeakSelf
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count >0) {
            weakSelf.selectImage =photos.firstObject;
            [self.addBtn setImage:weakSelf.selectImage forState:0];
            
        }
    weakSelf.isEditicon = YES;
        
    }];
    imagePickerVc.modalPresentationStyle = 0;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark -- 上传封面到七牛
-(void)upLoadImageToQINiu:(UIImage *)coverImg andBlock:(void (^)(NSString  *))imageBackBlock{
    
    if (self.kUploadIconImageToken) {
        
        NSData *data =UIImageJPEGRepresentation(coverImg, 0.8);
        
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *key = [NSString stringWithFormat:@"iOS%@.jpg", [formatter stringFromDate:[NSDate date]]];
        [upManager putData:data key:key token:self.kUploadIconImageToken
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (!kDictIsEmpty(resp)) {
                          !imageBackBlock ? : imageBackBlock([resp jsonString:@"key"]);
                      }else
                      {
                           [self stopLoadingAnimation];
                            self.bindBtn.userInteractionEnabled = YES;
                           [JMNotifyView showNotify:@"上传照片失败" isSuccessful:NO];
                      }
                  } option:nil];
    }else{
        [self getAvatarQiniuToken];
    }
}
- (BOOL)JudgeTheillegalCharacter:(NSString *)content{
    //提示 标签不能输入特殊字符
    NSString *str =  @"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    //@"^[A-Za-z0-9\\u4e00-\u9fa5]+$”;
    NSPredicate * emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}
//获取七牛头像token
-(void)getAvatarQiniuToken{
    [self showLoadingAnimation];
    WEAKSELF
    [[SmileHttpTool sharedInstance] getTokenFromQiNiu:@"" resultBlock:^(BOOL isSuccess, NSString *token) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        if (isSuccess) {
            strongSelf.kUploadIconImageToken = token;
        }
    }];
}
@end
